package xhwl.insurance.ui;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.RxPermissions;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.manager.JPushMgr;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.insurance.BaseFragmentActivity;
import xhwl.insurance.Constant;
import xhwl.insurance.R;
import xhwl.insurance.http.api.RegJPushApi;
import xhwl.insurance.http.api.UpdateLoginInfoApi;
import xhwl.insurance.http.bean.resp.ResponseError;
import xhwl.insurance.http.bean.resp2.HttpResp;
import xhwl.insurance.ui.fragment.FindFragment2;
import xhwl.insurance.ui.fragment.ForumFragment;
import xhwl.insurance.ui.fragment.MineFragment;
import xhwl.insurance.ui.fragment.SaleCardFragment;
import xhwl.insurance.upgrade.UpgradeEvent;
import xhwl.insurance.upgrade.UpgradeMgr;
import xhwl.insurance.util.AppUtil;
import xhwl.insurance.util.DimenUtil;
import xhwl.insurance.util.PermisionUtils;
import xhwl.insurance.util.SpUtil;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


public class MainActivity extends BaseFragmentActivity implements View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    private FrameLayout tabcontent;
    private ImageView ivTabSaleCard;
    private TextView tvTabSaleCard;
    private LinearLayout llayoutTabSaleCard,llayoutTabFind,llayoutTabForum;
    private ImageView ivTabMine,ivTabForum,ivTabFind;
    private TextView tvTabMine,tvTabForum,tvFind;
    private LinearLayout llayoutTabMine;
    public static MainActivity instance;
    private SaleCardFragment saleCardFragment;
    private MineFragment mineFragment;
    private ForumFragment forumFragment;
    private FindFragment2 findFragment;
    private Fragment fragmentByTag;
    private LinearLayout main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        manager = getSupportFragmentManager();
        DimenUtil.setStatusBar(this);
        setContentView(R.layout.activity_main);
        instance = this;
        if(getIntent().getStringExtra("BACK_STATE").equals("1")){
            changeFragment(3);
        }

    }

    @Override
    public void initViews() {
        main = (LinearLayout) findViewById(R.id.main);
        tabcontent = (FrameLayout) findViewById(R.id.tabcontent);
        ivTabSaleCard = (ImageView) findViewById(R.id.ivTabSaleCard);
        tvTabSaleCard = (TextView) findViewById(R.id.tvTabSaleCard);
        llayoutTabSaleCard = (LinearLayout) findViewById(R.id.llayoutTabSaleCard);
        ivTabMine = (ImageView) findViewById(R.id.ivTabMine);
        tvTabMine = (TextView) findViewById(R.id.tvMine);
        llayoutTabMine = (LinearLayout) findViewById(R.id.llayoutTabMine);

        ivTabForum = (ImageView) findViewById(R.id.ivTabForum);
        tvTabForum = (TextView) findViewById(R.id.tvTabForum);
        llayoutTabForum = (LinearLayout) findViewById(R.id.llayoutTabForum);

        ivTabFind = (ImageView) findViewById(R.id.ivTabFind);
        tvFind = (TextView) findViewById(R.id.tvFind);
        llayoutTabFind = (LinearLayout) findViewById(R.id.llayoutTabFind);
    }

    @Override
    protected void processOper() {
        super.processOper();
        boolean hasUpdateDeviceInfo= SpUtil.getBoolean(SpUtil.HAS_UPDATE_DEVICE_INFO,false);
        if(!hasUpdateDeviceInfo){
            String linkMobile=SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.LINK_MOBILE,"");
            String phoneId= AppUtil.getImei(mContext);
            String phoneUnion=android.os.Build.MODEL;
            String versonName=AppUtil.getVersionName(mContext);
            BaseApi api=new UpdateLoginInfoApi(linkMobile,phoneId,phoneUnion,versonName);
            HttpManager.getInstance().dealHttp(this,api,new OnNextListener<ResponseError>(){
                @Override
                public void onNext(ResponseError error) {
                    if(error!=null&&error.isSuccess()){
                        SpUtil.putBoolean(SpUtil.HAS_UPDATE_DEVICE_INFO,true);
                    }
                }
            });
        }
        requestPermission();
    }

    @Override
    public void initListener() {
        llayoutTabSaleCard.setOnClickListener(this);
        llayoutTabMine.setOnClickListener(this);
        llayoutTabForum.setOnClickListener(this);
        llayoutTabFind.setOnClickListener(this);
        llayoutTabSaleCard.performClick();
    }

    @Override
    public void loadData() {
        String memberId=SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID,"");
        if(!StringUtil.isEmpty(memberId)){
            registJPushId(memberId);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if (null != PermisionUtils.alertDialog)
            PermisionUtils.alertDialog.dismiss();
        if (null != instance)
            instance.finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llayoutTabSaleCard:
                changeFragment(0);
                break;
            case R.id.llayoutTabForum:
                changeFragment(1);
                break;
            case R.id.llayoutTabFind:
                changeFragment(2);
                break;
            case R.id.llayoutTabMine:
                changeFragment(3);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 判断是否接受通知
        boolean isPushOn = SPUtil.getCommon().getBoolean(SPUtil.Common.PUSH_ON, true);
        if (isPushOn) {
            JPushInterface.resumePush(getApplicationContext());
        } else {
            JPushInterface.stopPush(getApplicationContext());
        }
    }

    public void changeFragment(int tabpage) {
        transaction = manager.beginTransaction();
        resetTabView();
        hide();
        if (null!=findFragment){//切换页面时 关掉视频声音
            findFragment.onPause();
        }

        switch (tabpage) {
            case 0:
//                if (saleCardFragment == null) {
                saleCardFragment = null;
                saleCardFragment = new SaleCardFragment();
                transaction.add(R.id.tabcontent, saleCardFragment, "SaleCardFragment");
//                } else {
//                    transaction.show(saleCardFragment);
//                }
                ivTabSaleCard.setImageDrawable(getResources().getDrawable(R.drawable.icon_home2));
                tvTabSaleCard.setTextColor(getResources().getColor(R.color.tab_text_select));
                break;
            case 1:
                forumFragment = null;
                forumFragment = new ForumFragment();
                transaction.add(R.id.tabcontent, forumFragment);
                ivTabForum.setImageDrawable(getResources().getDrawable(R.drawable.icon_forum2));
                tvTabForum.setTextColor(getResources().getColor(R.color.tab_text_select));
                break;

            case 2:
                findFragment = null;
                findFragment = new FindFragment2();
                transaction.add(R.id.tabcontent, findFragment);
                ivTabFind.setImageDrawable(getResources().getDrawable(R.drawable.icon_find2));
                tvFind.setTextColor(getResources().getColor(R.color.tab_text_select));
                break;

            case 3:
                //有时网络请求失败无法显示页面信息,只能每次都重新加载新的fragment
//                if (mineFragment == null) {
                mineFragment = null;
                mineFragment = new MineFragment();
                transaction.add(R.id.tabcontent, mineFragment);
//                } else {
//                    transaction.show(mineFragment);
//                }
                ivTabMine.setImageDrawable(getResources().getDrawable(R.drawable.tab_mine_select));
                tvTabMine.setTextColor(getResources().getColor(R.color.tab_text_select));
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hide() {
        if (saleCardFragment != null) {
            transaction.hide(saleCardFragment);

        }
        if (forumFragment != null) {
            transaction.hide(forumFragment);
        }
        if (findFragment != null) {
            transaction.hide(findFragment);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
    }

    public void resetTabView() {
        ivTabSaleCard.setImageDrawable(getResources().getDrawable(R.drawable.icon_home));
        ivTabMine.setImageDrawable(getResources().getDrawable(R.drawable.tab_mine_normal));

        ivTabForum.setImageDrawable(getResources().getDrawable(R.drawable.icon_forum));
        ivTabFind.setImageDrawable(getResources().getDrawable(R.drawable.icon_find));

        tvTabForum.setTextColor(getResources().getColor(R.color.tab_text_normal));
        tvFind.setTextColor(getResources().getColor(R.color.tab_text_normal));

        tvTabMine.setTextColor(getResources().getColor(R.color.tab_text_normal));
        tvTabSaleCard.setTextColor(getResources().getColor(R.color.tab_text_normal));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    new UpgradeMgr().checkVersion(this);
                } else {
                    PermisionUtils.dialog(this, "读取手机存储");
                }
                break;
        }
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onEvent(Object obj) {
        if (obj instanceof UpgradeEvent) {
            UpgradeEvent event = (UpgradeEvent) obj;
            if (event.isDownloadComplete()) {
                new UpgradeMgr().checkVersion(this);
            } else if (event.isStartDownload()) {
//                ToastUtil.showToast(this, "开始下载...");
            } else if (event.isNewest()) {
//                ToastUtil.showToast(this, "当前已是最新版本");
            } else if (event.isDownloading()) {
//                ToastUtil.showToast(this, "下载中...");
            }
        }
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            new UpgradeMgr().checkVersion(MainActivity.this);
                        } else {
                            Log.e(TAG,
                                    "用户拒绝开启存储");
                            PermisionUtils.dialog(MainActivity.this, "读取手机存储");
                        }
                    }

                });
    }
    private void registJPushId(final String memberId) {
        boolean isRegisted = SpUtil.getBoolean(SpUtil.IS_JPUSH_REGIST,false);
         if(!isRegisted) {
             JPushMgr.getInstance().registJPushId(mContext, new JPushMgr.RegistJpushCallback() {

                 @Override
                 public void onResult(boolean result, final String msg) {
                     // TODO Auto-generated method stub
                     if (result) {
                         String appKey = AppUtil.getMetadata(mContext, Constant.JPUSH_APP_KEY);
                         RegJPushApi api = new RegJPushApi(memberId, msg, appKey);
                         HttpManager.getInstance().dealHttp(MainActivity.this, api, new OnNextListener<HttpResp>() {
                             @Override
                             public void onNext(HttpResp resp) {
                                 if (resp != null && resp.isOk()) {
                                     XHLog.e("regist jpush id success id=" + msg);
                                     SpUtil.putBoolean(SpUtil.IS_JPUSH_REGIST,true);
                                     JPushInterface.resumePush(mContext.getApplicationContext());
                                 } else {
                                     XHLog.e("regist jpush id fail id=" + msg);
                                 }
                             }
                         });
                     }
                 }
             });
         }
    }
}
